package serviceImp;

import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import dao.StoptimeHome;
import dao.TrailerHome;
import dao.VideoHome;

import pojo.Movie;
import pojo.Stoptime;
import pojo.Trailer;
import pojo.User;
import pojo.Video;
import service.IVideoService;

public class VideoService implements IVideoService {

    
    private static final Logger _logger = Logger.getLogger(VideoService.class);
    
    private VideoHome videoDao;
    
    private TrailerHome trailerDAO;
    
    private StoptimeHome stoptimeDAO;

    
    public VideoService(){
	
    }
    
    public void setVideoDao(VideoHome videoDao) {
        this.videoDao = videoDao;
    }

    public void setTrailerDAO(TrailerHome trailerDAO) {
        this.trailerDAO = trailerDAO;
    }

    public void setStoptimeDAO(StoptimeHome stoptimeDAO) {
        this.stoptimeDAO = stoptimeDAO;
    }

    public Video getVideoById(int vid) {
	return videoDao.findById(vid);
    }

    public List<Video> getMovieAllVideos(int movie_id) {
	
	Video examlp =  new Video();
	
	examlp.setVMovie(movie_id);
	
	List<Video> list = videoDao.findByExample(examlp);
	
	_logger.log(Level.INFO, String.format("%d video found", list.size()));
	
	return list;
    }

    public List<Video> getTvVideos(int tv_id) {
	
	Video examlp =  new Video();
	
	examlp.setVTvshow(tv_id);
	
	List<Video> list = videoDao.findByExample(examlp);
	
	_logger.log(Level.INFO, String.format("%d video found", list.size()));
	
	return list;
    }

    public void addVideo(Video video) {
	
	try {
	    videoDao.attachDirty(video);
	} catch (Exception e) {
	    _logger.log(Level.ERROR, "Insert new video error");
	}

    }

    public void updateVideo(Video video) {
	try {
	    videoDao.attachDirty(video);
	} catch (Exception e) {
	    _logger.log(Level.ERROR, "Insert new video error");
	}

    }

    public List<Trailer> getVideoTrailer(Video video) {
	
	List<Trailer> list = trailerDAO.findByVideo(video.getVId());
	
	_logger.log(Level.INFO, String.format("%d video trailer found", list.size()));

	
	if (list.size()==0) {
	    return null;
	}else{
	    return list; 
	}
    }

    public int getLastStoppoint(User user, Video video) {
	
	Stoptime example = new Stoptime();
	
	example.setUser(user);
	
	example.setVideo(video);
	
	List<Stoptime> stoptime = stoptimeDAO.findByExample(example);
	if (stoptime.size()>0) {
	    return stoptime.get(0).getStopMinutes();
	}else{
	    return 0;
	}
    }

}
